package com.example.libpro.DBEntity;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;

public class PermissionUtils {
    // 权限请求码
    public static final int STORAGE_PERMISSION_REQUEST_CODE = 100;

    /**
     * 检查并申请存储权限
     */
    public static boolean checkAndRequestStoragePermissions(Activity activity) {
        List<String> neededPermissions = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // Android 13+
            // Android 13+ 访问公共目录（如Download）无需申请 WRITE_EXTERNAL_STORAGE，但需要 READ 权限
            // 若仅操作非媒体文件（如数据库文件），申请 READ_EXTERNAL_STORAGE 即可
            if (ContextCompat.checkSelfPermission(activity,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                neededPermissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        } else { // Android 12 及以下
            // 需要同时申请读写权限
            if (ContextCompat.checkSelfPermission(activity,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                neededPermissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(activity,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                neededPermissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }

        // 申请缺失的权限
        if (!neededPermissions.isEmpty()) {
            ActivityCompat.requestPermissions(activity,
                    neededPermissions.toArray(new String[0]),
                    STORAGE_PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }
}